<script setup lang="ts">
  import { ref } from 'vue';
  import {
    queryAllStaffArrange,
    editStaffArrange,
  } from '@/api/organization/work-scheduling';
  import { queryList } from '@/api/organization/nursing-home';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import { queryStateByCode } from '@/api/dict';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import { useAutoRequest } from '@/hooks/arco/useAutoLoading';
  import dayjs from 'dayjs';
  import { Message } from '@arco-design/web-vue';
  import ListSelect from '@/components/list-select/index.vue';

  const [saveLoading, save] = useAutoRequest(editStaffArrange);

  const arrangeTypeMap = ref<Record<string, string>>({});

  const arrangeDataArr = ref<any[]>([]);

  const monthDataArr = ref<any[]>([]);
  const weekText = ['一', '二', '三', '四', '五', '六', '日'];

  const today = dayjs().startOf('date');

  const todayIndex = ref(-1);

  const weekPage = ref(0);

  const branchTable = useSkeleton<any>({
    apiFun: queryList,
  });

  const radioOptions = useSelectOption({
    initQueryParams: ['StaffArrangeType'],
    apiFun: queryStateByCode,
    fieldNames: {
      value: 'stateValue',
      label: 'stateLabel',
    },
    onSuccess(data: any[]) {
      // console.log(data);
      arrangeTypeMap.value = data.reduce((prev, current) => {
        prev[current.value] = current.label;
        return prev;
      }, {});
    },
  });

  const radioValue = ref('');

  const currentObj = ref({
    staffId: null,
    arrangeDate: null,
  });

  // 获取本周的日期
  function getCurrentWeekDates() {
    const dayOfWeek = today.day();

    const startOfWeek = today.subtract(
      dayOfWeek === 0 ? 6 : dayOfWeek - 1,
      'day'
    );

    const useDay = startOfWeek.add(weekPage.value, 'week');

    const weekDates = [];
    const monthMap = new Map<string, number>();

    todayIndex.value = -1;

    for (let i = 0; i < 7; i += 1) {
      const date = useDay.add(i, 'day');
      weekDates.push({
        date,
        dayStr: date.format('DD'),
        week: weekText[i],
      });
      if (today.isSame(date)) {
        todayIndex.value = i;
      }
      let monthDay = 0;
      const month = date.format('YYYY-MM');

      if (monthMap.get(month)) {
        monthDay = monthMap.get(month) as number;
      }
      monthMap.set(month, monthDay + 1);
    }

    const monthArr: any[] = [];

    monthMap.forEach((value, key) => {
      monthArr.push({
        month: key,
        dates: value,
      });
    });

    arrangeDataArr.value = weekDates;
    monthDataArr.value = monthArr;
  }

  getCurrentWeekDates();

  const skView = useSkeleton({
    immediate: false,
    apiFun: queryAllStaffArrange,
  });

  const popupVisibleIndex = ref();

  const onRadioChange = (staff: any, day: any) => {
    save({
      staffId: currentObj.value.staffId,
      arrangeDate: currentObj.value.arrangeDate,
      arrangeType: radioValue.value,
    }).then(() => {
      day.arrangeType = radioValue.value;
      Message.success('保存成功！');
      popupVisibleIndex.value = null;
    });
  };

  const onVisibleChange = (
    visible: boolean,
    staff: any,
    arrangeIndex: number
  ) => {
    if (visible) {
      const day = staff.arrangeData[arrangeIndex];
      if (!day) {
        radioValue.value = '';
        return;
      }
      currentObj.value = {
        staffId: staff.staffId,
        arrangeDate: day.arrangeDate,
      };
      if (day.arrangeType) {
        radioValue.value = day.arrangeType.toString();
      } else {
        radioValue.value = '';
      }
    }
  };

  const checkIndex = ref(-1);

  const currentBranch = ref();

  const onItemCheck = (item: any, index: number) => {
    checkIndex.value = index;
    currentBranch.value = item;
    skView.execute(item.id, weekPage.value);
    getCurrentWeekDates();
  };

  const perviousWeek = () => {
    if (!currentBranch.value) {
      return;
    }
    weekPage.value -= 1;
    skView.execute(currentBranch.value.id, weekPage.value);
    getCurrentWeekDates();
  };

  const nextWeek = () => {
    if (!currentBranch.value) {
      return;
    }
    weekPage.value += 1;
    skView.execute(currentBranch.value.id, weekPage.value);
    getCurrentWeekDates();
  };

  const getCurrentLabel = (index: number, staff: any) => {
    if (staff.arrangeData && staff.arrangeData.length > 0) {
      const date = staff.arrangeData[index];
      if (!date) {
        return '-';
      }
      if (date.arrangeType === null) {
        return '-';
      }
      return arrangeTypeMap.value[date.arrangeType];
    }
    return '-';
  };

  const popupVisible = (staffId: string, index: number) => {
    const obj = popupVisibleIndex.value;
    if (!obj) {
      return false;
    }
    return obj.staffId === staffId && obj.index === index;
  };

  const showPopupVisible = (staff: any, index: number) => {
    popupVisibleIndex.value = {
      staffId: staff.staffId,
      index,
    };
    onVisibleChange(true, staff, index);
  };

  const hiddenPopup = () => {
    popupVisibleIndex.value = null;
  };
</script>

<template>
  <div
    id="scheduling-wrapper"
    class="h-full flex gap-5 flex-1 overflow-visible relative"
    @click="hiddenPopup"
  >
    <skeleton-view
      v-slot="{ data }"
      class="w-[280px]"
      v-bind="branchTable.bindProps"
    >
      <ListSelect :data="data" @change="onItemCheck" />
    </skeleton-view>

    <div
      class="flex-1 overflow-y-auto h-full relative py-2 px-4 border rounded shadow"
    >
      <skeleton-view v-slot="{ data }" v-bind="skView.bindProps">
        <div class="p-2 flex flex-col">
          <div class="flex justify-between">
            <h3 class="text-xl font-semibold">{{ currentBranch.name }}</h3>
            <a-space class="self-end mb-2">
              <a-button type="primary" @click="perviousWeek">
                <div class="flex items-center">
                  <icon-left />
                  <span>上一周</span>
                </div>
              </a-button>
              <a-button type="primary" @click="nextWeek">
                <div class="flex items-center">
                  <span>下一周</span>
                  <icon-right />
                </div>
              </a-button>
            </a-space>
          </div>
          <table class="scheduling-table">
            <colgroup>
              <col style="width: 9%" />
              <col style="width: 9%" />
              <col style="width: 8%" />
              <col v-for="item in 7" :key="item" style="width: 10%" />
            </colgroup>
            <thead>
              <tr>
                <th rowspan="2">
                  <span class="font-semibold">姓名</span>
                </th>
                <th rowspan="2">
                  <span class="font-semibold">职位</span>
                </th>
                <th rowspan="2">
                  <span class="font-semibold">工作状态</span>
                </th>
                <th
                  v-for="(monthItem, index) in monthDataArr"
                  :key="index"
                  :colspan="monthItem.dates"
                >
                  <span class="text-[16px] font-semibold">
                    {{ monthItem.month }}
                  </span>
                </th>
              </tr>
              <tr>
                <th
                  v-for="(item, index) in arrangeDataArr"
                  :key="index"
                  :class="[
                    {
                      'is-today': todayIndex === index,
                    },
                  ]"
                >
                  <div class="flex flex-col">
                    <span>{{ item.dayStr }}</span>
                    <span class="text-[12px]">周{{ item.week }}</span>
                  </div>
                </th>
              </tr>
            </thead>

            <tbody>
              <tr v-for="staff in data" :key="staff.staffId">
                <td>
                  <div>
                    <span>{{ staff.staffName }}</span>
                  </div>
                </td>
                <td>
                  <div>
                    <span>{{ staff.position }}</span>
                  </div>
                </td>
                <td>
                  <dict-tag :value="staff.workingStatus" type="StaffStatus" />
                </td>
                <td
                  v-for="(_, arrangeIndex) in 7"
                  :key="arrangeIndex"
                  class="sc-td"
                  :class="[
                    {
                      'is-today': todayIndex === arrangeIndex,
                    },
                  ]"
                >
                  <a-popover
                    popup-container="#scheduling-wrapper"
                    trigger="click"
                    position="top"
                    :popup-visible="popupVisible(staff.staffId, arrangeIndex)"
                  >
                    <div
                      class="scheduling-item"
                      @click.stop="showPopupVisible(staff, arrangeIndex)"
                    >
                      <span>{{ getCurrentLabel(arrangeIndex, staff) }} </span>
                    </div>
                    <template #content>
                      <div class="flex flex-col" @click.stop>
                        <div class="flex items-center gap-2">
                          <span class="pop-title font-semibold">
                            设置排班信息
                          </span>
                          <span class="w-[20px]">
                            <icon-loading v-if="saveLoading" />
                          </span>
                        </div>

                        <a-radio-group
                          v-model="radioValue"
                          direction="vertical"
                          v-bind="radioOptions.bindProps"
                          @change="
                            onRadioChange(
                              staff,
                              staff.arrangeData[arrangeIndex]
                            )
                          "
                        />
                      </div>
                    </template>
                  </a-popover>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </skeleton-view>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .scheduling-wrapper {
    overflow-x: auto;
    overflow-y: visible;
  }

  .pop-title {
    color: #333333;
    font-size: 16px;
  }
  .scheduling-table {
    border: 1px solid #dcdcdc;
    border-collapse: collapse;
    white-space: nowrap;
    width: 100%;

    th,
    td {
      border: 1px solid #dcdcdc;
    }

    th {
      font-weight: 500;
    }

    th,
    td {
      padding: 6px 6px;
      text-align: center;
    }

    .scheduling-item {
      height: 100%;
      text-align: center;
      cursor: pointer;
      width: 100%;
    }

    .sc-td {
      // width: 120px;
      text-align: center;
    }

    .is-today {
      background-color: #e8f3ff;
      color: #333333;
    }
  }
</style>
